package one.stand.controller.index;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.cache.IndexCacheModel;
import com.jmp.api.dto.*;
import com.jmp.api.util.LabelUtil;
import com.jmp.base.ArticleApi;
import com.jmp.base.DynamicApi;
import com.jmp.base.dto.LiveListRequest;
import com.jmp.base.dto.LiveListVo;
import com.jmp.feign.AppIndexGoodsFeign;
import com.jmp.feign.BannerFeign;
import com.jmp.feign.LiveFeign;
import com.jmp.service.api.admin.AppIndexGoodsApi;
import com.jmp.service.api.admin.BannerApi;
import com.jmp.service.api.admin.dto.AppIndexGoodsRequest;
import com.jmp.service.api.admin.dto.AppIndexGoodsResponse;
import com.jmp.service.api.admin.dto.BannerListDto;
import com.jmp.service.api.admin.dto.BannerListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.Company2Dto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.ArticleApiCrmAppMapper;
import one.stand.model.Article;
import one.stand.model.BusinessCard;
import one.stand.model.Goods;
import one.stand.model.ResultModel;
import one.stand.service.*;
import one.stand.service.sys.UserContentService;
import one.stand.util.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "推荐")
@RestController
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private AppIndexGoodsFeign appIndexGoodsFeign;
    @Autowired
    private LiveFeign liveFeign;
    @Autowired
    private BannerFeign bannerFeign;

    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ArticleApiCrmAppMapper articleApiCrmAppMapper;

    @ApiOperation(value = "1:首页前面banner、icon、card")
    @GetMapping("")
    public ResultModel<IndexResponse> index() {
        final RequestContext requestContext = RequestContextHolder.getRequestContext();
        final Integer companyId = requestContext.isCard() ? requestContext.getUser().getCompanyId() : ArticleApi.DEFAULT_COMPANYID;

        IndexCacheModel indexCacheModel = new IndexCacheModel(redisUtil, companyId);
        IndexResponse responseCache = indexCacheModel.get();
        if (Objects.nonNull(responseCache)) {
            return ResultModel.success(responseCache);
        }

        //banner
        List<IndexResponse.Banner> banners = getBannerList(BannerApi.COMPANY_ID_PLATFORM, BannerApi.BANNER_TYPE_JSX_INDEX, null);

        //精选品牌
        BannerListDto bannerListDto = BannerListDto.builder()
                .companyId(BannerApi.COMPANY_ID_PLATFORM)
                .bannerType(BannerApi.BANNER_TYPE_JSX_BRAND_2)
                .refId(null)
                .build();
        bannerListDto.setAll();
        ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
        AssertUtil.isTrue(bannerListVoResultModel);
        List<IndexResponse.Icon> iconList = ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), type -> {
            return IndexResponse.Icon.builder()
                    .name(type.getMemo())
                    .children(getBannerList(BannerApi.COMPANY_ID_PLATFORM, BannerApi.BANNER_TYPE_JSX_BRAND_2, type.getId()))
                    .build();
        });

        //头条下轮播图
        List<IndexResponse.Banner> cardList = getBannerList(BannerApi.COMPANY_ID_PLATFORM, BannerApi.BANNER_TYPE_JSX_INDEX_CARD, null);

        //专题
        List<IndexResponse.Banner> subjectList = getBannerList(BannerApi.COMPANY_ID_PLATFORM, BannerApi.BANNER_TYPE_SUBJECT, null);

        //头条
        String excludeLabelIds = null;//登录且无名片时，获取标签【商家、经销商】下的头条
        if (requestContext.isLogin() && !requestContext.isCard()) {
            Integer supplierLabelId = companyBaseService.getLabelId(CompanyBaseService.LABEL_SUPPLIER);
            Integer jxsLabelId = companyBaseService.getLabelId(CompanyBaseService.LABEL_JXS);
            excludeLabelIds = SqlUtil.in(Lists.newArrayList(String.valueOf(supplierLabelId), String.valueOf(jxsLabelId)));
        }
        //置顶
        PageHelper.startPage(1, 1);
        List<Article> articles = articleApiCrmAppMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, ArticleApi.POSITION_TOP, null, excludeLabelIds, null, null);
        List<IndexResponse.Top> articleTops = ConvertUtils.list(articles, article -> {
            return IndexResponse.Top.builder()
                    .articleId(article.getId())
                    .title(article.getTitle())
                    .build();
        });
        //最新
        PageHelper.startPage(1, 3);
        articles = articleApiCrmAppMapper.selectTop(UserContentService.TYPE_COMPANY, companyId, UserContentService.TYPE_ARTICLE, null, null, excludeLabelIds, null, ArticleApi.POSITION_TOP);
        List<IndexResponse.Top> articleList = ConvertUtils.list(articles, article -> {
            return IndexResponse.Top.builder()
                    .articleId(article.getId())
                    .title(article.getTitle())
                    .build();
        });

        //直播短视频
        com.jmp.base.dto.LiveListRequest liveListRequest = LiveListRequest.builder()
                .build();
        liveListRequest.setPageInit(1, 3);
        ResultModel<LiveListVo> liveListVoResultModel = liveFeign.list(liveListRequest);
        AssertUtil.isTrue(liveListVoResultModel);
        PageResponse2<IndexResponse.Live> livePage = ConvertUtils.page2(liveListVoResultModel.getData().getLivePage(), live -> {
            BusinessCard businessCard = businessCardBaseService.getCustomer(live.getCardId());
            Company2Dto company = companyBaseService.get2(businessCard.getCompanyId());

            IndexResponse.Video video = null;
            boolean isVideo = live.getStatus() == 2;
            if (isVideo) {
                video = IndexResponse.Video.builder()
                        .roomId(live.getRoomId())
                        .name(live.getTitle())
                        .photo(live.getPhoto())
                        .videoUrl(live.getReplayUrl())
                        .userCurrentRoomId(live.getUserCurrentRoomId())

                        .cardId(businessCard.getCardId())
                        .cardImg(businessCard.getLogo())
                        .cardName(businessCard.getName())
                        .userId(businessCard.getUserId())
                        .userCollectFlag(BooleanUtils.toInteger(requestContext.isLogin() && recordPublicService.isCollection(requestContext.getUser().getUserId(), RecordPublicService.ITEMTYPE_USER, businessCard.getUserId())))

                        .viewNum(recordPublicService.getPopularity(SeeRecordEnums.LIVE.getCode(), live.getRoomId()))
                        .collectNum(recordPublicService.getCollectionCount(RecordPublicService.ITEMTYPE_LIVE_ROOM, live.getRoomId()))
                        .collectFlag(BooleanUtils.toInteger(requestContext.isLogin() && recordPublicService.isCollection(requestContext.getUser().getUserId(), RecordPublicService.ITEMTYPE_LIVE_ROOM, live.getRoomId())))
                        .commentNum(recordPublicService.countCommentByType(DynamicApi.COMMENT_TYPE_VIDEO, live.getRoomId()))
                        .build();
            }

            return IndexResponse.Live.builder()
                    .roomId(live.getRoomId())
                    .videoType(BooleanUtils.toInteger(isVideo))
                    .photo(OneStringUtils.photoResize(live.getPhoto()))
                    .title(live.getTitle())
                    .status(LabelUtil.getLiveStatus(live.getStatus()))

                    .viewNum(live.getViewNum() + "人观看")//直播中才显示观看人数
                    .collectNum(recordPublicService.getCollectionCount(RecordPublicService.ITEMTYPE_LIVE_ROOM, live.getRoomId()))

                    .userImg(company.getCompanyLogo())
                    .userName(company.getCompanyName())

                    .video(video)
                    .build();
        });

        IndexResponse response = IndexResponse.builder()
                .bannerList(banners)
                .iconList(iconList)
                .cardList(cardList)
                .subjectList(subjectList)
                .articleTop(OneListUtil.isNotEmpty(articleTops) ? articleTops.get(0) : null)
                .articleList(articleList)
                .liveList(livePage.getList())
                .build();

        indexCacheModel.save(response);

        return ResultModel.success(response);
    }

    @ApiOperation("2:专题子页")
    @GetMapping("/subject")
    public ResultModel<IndexSubjectResponse> subject(@RequestAttribute IndexSubjectRequest request) {
        BannerListDto bannerListDto = BannerListDto.builder()
                .companyId(BannerApi.COMPANY_ID_PLATFORM)
                .bannerType(null)
                .refId(request.getBannerId())
                .build();
        bannerListDto.setAll();
        ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
        AssertUtil.isTrue(bannerListVoResultModel);
        List<IndexSubjectResponse.Banner> cardBannerList = ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), companyBanner -> IndexSubjectResponse.Banner.builder()
                .bannerId(companyBanner.getId())
                .source(companyBanner.getSource())
                .event(companyBanner.getEvent())
                .eventId(companyBanner.getEventId())
                .memo(companyBanner.getMemo())
                .sizeRate(companyBanner.getSizeRate())
                .build());
        IndexSubjectResponse response = IndexSubjectResponse.builder()
                .subjectList(cardBannerList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("2:商品列表")
    @GetMapping("/goods")
    public ResultModel<IndexGoodsResponse> goods(@RequestAttribute IndexGoodsRequest request) {

        AppIndexGoodsRequest goodsRequest = AppIndexGoodsRequest.builder()
                .type(AppIndexGoodsApi.TYPE_INDEX)
                .build();
        goodsRequest.setPageNum(request.getPageNum());
        goodsRequest.setPageSize(request.getPageSize());
        ResultModel<AppIndexGoodsResponse> resultModel = appIndexGoodsFeign.list(goodsRequest);
        AssertUtil.isTrue(resultModel);

        PageResponse2<AppIndexGoodsResponse.Goods> goodsPage = resultModel.getData().getGoodsList();
        if (OneListUtil.isNotEmpty(goodsPage.getList())) {
            Collections.shuffle(goodsPage.getList());
        }

        PageResponse2<IndexGoodsResponse.Goods> goodsList = ConvertUtils.page2(goodsPage, goods -> {
//            List<GoodsTypeDto> platformTypes = goodsBaseService.getTypes(goods.getGoodsId());
//            if (OneListUtil.isEmpty(platformTypes)) return null;

            Goods goods1 = goodsBaseService.get(goods.getGoodsId());
            Long popularityNum = recordPublicService.getPopularity(SeeRecordEnums.PRODUCT.getCode(), goods1.getGoodsId());
            boolean hasVr = StringUtils.isNoneBlank(goods1.getQjVrUrl());
            boolean hasAr = goodsBaseService.hasAr(goods1.getGoodsId());
            boolean hasVideo = StringUtils.isNoneBlank(goods1.getVideoUrl());
            boolean hasZkgx = companyBaseService.hasZkgx(goods1.getCompanyId());
            Company2Dto company = companyBaseService.get2(goods1.getCompanyId());

            return IndexGoodsResponse.Goods.builder()
                    .goodsId(goods1.getGoodsId())
                    .goodsName(goods1.getGoodsName())
                    .photo(OneStringUtils.photoResize(goodsPhotoService.getPath(goods1.getGoodsId())))
                    .popularityNum(popularityNum)
                    .labels(LabelUtil.getLabels(hasVr, hasAr, hasVideo, hasZkgx))
                    .companyName(Objects.nonNull(company) ? company.getCompanyName() : null)
                    .build();
        });

        IndexGoodsResponse response = IndexGoodsResponse.builder()
                .goodsPage(goodsList)
                .build();
        return ResultModel.success(response);
    }

    private List<IndexResponse.Banner> getBannerList(Integer companyId, Integer bannerType, Integer refId) {
        BannerListDto bannerListDto = BannerListDto.builder()
                .companyId(companyId)
                .bannerType(bannerType)
                .refId(refId)
                .build();
        bannerListDto.setAll();
        ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
        AssertUtil.isTrue(bannerListVoResultModel);
        return ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), companyBanner -> IndexResponse.Banner.builder()
                .bannerId(companyBanner.getId())
                .source(companyBanner.getSource())
                .event(companyBanner.getEvent())
                .eventId(companyBanner.getEventId())
                .memo(companyBanner.getMemo())
                .sizeRate(companyBanner.getSizeRate())
                .build());
    }
}
